<script setup>
    import {
        Edit,
        Delete,
        BellFilled
    } from '@element-plus/icons-vue'
    import { QuillEditor } from '@vueup/vue-quill'
    import '@vueup/vue-quill/dist/vue-quill.snow.css'
    import {reactive,ref} from 'vue'
    import moment from 'moment'
    // 导入 ExcelJS 库
    import ExcelJS from 'exceljs/dist/exceljs.min.js';
    const informs = ref([{
        "informId": 3,
        "content": "嗨嗨嗨",
        "status": "已查看",
        "startTime": "2023-11-02 12:06:59",
        "endTime": "2023-12-02 12:06:59",
        "title":""
    }])
    //分页
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(20)
    const handleSizeChange = (val) => {
        pageSize.value = val;
        InformListByPage(currentPage.value, pageSize.value);
    }
    const handleCurrentChange = (val) => {
        currentPage.value = val;
        InformListByPage(currentPage.value, pageSize.value);
    }
    //声明一个异步的函数
    import {
        InformListByPageService,
        InformAddService,
        InformUpdateService,
        InformDeleteService,
        InformUpdateStatusService
    } from '@/api/inform.js'
    const InformListByPage = async (currentPage, pageSize) => {
        let result = await InformListByPageService(currentPage, pageSize);
        result.data.rows.forEach(row => {
            if (row.startTime) {
                row.startTime = moment(row.startTime).format('YYYY/MM/DD/HH:mm:ss');
            }
            if (row.endTime) {
                row.endTime = moment(row.endTime).format('YYYY/MM/DD/HH:mm:ss');
            }
        });
        total.value = result.data.total;
        informs.value = result.data.rows;
    }
    InformListByPage();

    //控制添加弹窗
    const dialogVisible = ref(false)

    //添加数据模型
    const informModel = ref({
        title:'',
        content: '',
        startTime: '',
        endTime: '',
    })
    const id = ref({
        informId: ''
    })
    //添加表单校验
    const rules = {
        title:[{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
        },],
        content: [{
            required: true,
            message: '请输入内容',
            trigger: 'blur'
        }, ],
        startTime: [{
            required: true,
            message: '请输入开始时间',
            trigger: 'blur'
        }, ],
        endTime: [{
            required: true,
            message: '请输入结束时间',
            trigger: 'blur'
        }, ]
    }
    import {
        ElMessage,
        ElMessageBox
    } from 'element-plus'
    //调用接口添加数据
    const addInform = async () => {
        informModel.value.startTime = moment(informModel.value.startTime).format('YYYY/MM/DD/HH:mm:ss');
        informModel.value.endTime = moment(informModel.value.endTime).format('YYYY/MM/DD/HH:mm:ss');
        //调用接口
        console.log(informModel.value);
        let result = await InformAddService(informModel.value);
        if(result.code===1){
            ElMessage.success('添加成功')
        }else{
            ElMessage.error(result.msg)
        }

        InformListByPage(currentPage.value, pageSize.value);
        dialogVisible.value = false;
    }

    //定义变量，控制标题的展示
    const title = ref('')
    //展示编辑弹窗
    const showDialog = (row) => {
    dialogVisible.value = true;
    title.value = '编辑公告';
    // 数据拷贝
    informModel.value.content = row.content;
    if(myQuillEditor.value){
        myQuillEditor.value.setHTML(informModel.value.content);
    }
    informModel.value.status = row.status;
    informModel.value.startTime = row.startTime;
    informModel.value.endTime = row.endTime;
    informModel.value.title = row.title;
    // console.log(informModel.value.content)
    // 将 row.content 的值赋给 newContent
    newContent.value = row.content;
    data.content = row.content;
    // 扩展ID属性，需要传输给后台
    informModel.value.informId = row.informId;
}

    //编辑
    const updateInform = async () => {
        informModel.value.startTime = moment(informModel.value.startTime).format('YYYY/MM/DD/HH:mm:ss');
        informModel.value.endTime = moment(informModel.value.endTime).format('YYYY/MM/DD/HH:mm:ss');
        //调用接口
        let result = await InformUpdateService(informModel.value);
        if(result.code===1){
            ElMessage.success('修改成功')
        }else {
            ElMessage.error(result.msg);
        }
        //调用获取所有分类的函数
        InformListByPage(currentPage.value, pageSize.value);
        dialogVisible.value = false;
    }
    //清空模型的数据
    const clearData = () => {
        informModel.value.title='';
        informModel.value.content = '';
        informModel.value.status = '';
        informModel.value.startTime = '';
        informModel.value.endTime = '';
        if(myQuillEditor.value){
        myQuillEditor.value.setHTML(informModel.value.content);
    }
    }
    //删除
    const deleteInform = async (row) => {
        //提示用户
        ElMessageBox.confirm(
                '你即将要删除该信息，确认吗?',
                '温馨提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async () => {
                //调用接口
                await InformDeleteService(row.informId);
                //刷新列表
                InformListByPage(currentPage.value, pageSize.value);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });

            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
    }

    //修改通知状态
    const updateStatus = async (row) => {
        id.value.informId = row.informId
        informModel.value.startTime = moment(informModel.value.startTime).format('YYYY/MM/DD/HH:mm:ss');
        informModel.value.endTime = moment(informModel.value.endTime).format('YYYY/MM/DD/HH:mm:ss');
        //调用接口
        await InformUpdateStatusService(id.value);
        //刷新列表
        InformListByPage(currentPage.value, pageSize.value);
        ElMessage({
            type: 'success',
            message: '查看成功',
        });
    }

    const multipleSelection = ref([])
    const deleteSelected = () => {
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: 'error',
                message: '并不存在数据',
            });
            return;
        }
        performDelete();
    }
    //异步删除方法
    const performDelete = async () => {
        try {
            for (const selectedItem of multipleSelection.value) {
                await InformDeleteService(selectedItem.informId);
            }
            InformListByPage(currentPage.value, pageSize.value);
            ElMessage({
                type: 'success',
                message: '批量删除成功',
            });
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '删除选定项目时出错',
            });
        }
    }
    const handleSelectionChange = (val) => {
        multipleSelection.value = val
    }
    // 导出
    const exportSelected = () => {
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: 'error',
                message: '请选择要导出的数据',
            });
            return;
        }

        // 创建一个新的工作簿
        const workbook = new ExcelJS.Workbook();

        // 添加一个工作表
        const worksheet = workbook.addWorksheet('Sheet1');

        // 设置表头信息
        worksheet.addRow(['标题','内容', '状态', '品牌', '开始时间', '结束时间']);

        // 获取选择的数据
        const selectedData = multipleSelection.value;

        // 将数据添加到工作表中
        selectedData.forEach(row => {
            worksheet.addRow([
                row.title,
                row.content,
                row.status,
                row.startTime,
                row.endTime
            ]);
        });

        // 将工作簿保存为Excel文件
        workbook.xlsx.writeBuffer()
            .then(buffer => {
                const blob = new Blob([buffer], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                const fileName = '通知数据.xlsx';

                // 创建下载链接并触发下载
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                link.click();

                ElMessage({
                    type: 'success',
                    message: '导出成功',
                });
            })
            .catch(error => {
                console.error('导出Excel文件时出错:', error);
                ElMessage({
                    type: 'error',
                    message: '导出失败',
                });
            });
    }
  const data = reactive({
    content: '',
    editorOption: {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'direction': 'rtl' }],
          [{ 'color': [] }, { 'background': [] }]
        ]
      },
      placeholder: '请输入内容...'
    }
  })
  const newContent = ref()
  const onContentChange = (newContent) => {
    // 将编辑器的文本内容更新到 informModel.content 中
    informModel.value.content = newContent;
    data.content = newContent;
  }


  const myQuillEditor = ref(null)

  const informDialog = ref(false)
  const showInform =async(row)=>{
    informDialog.value = true;
    // if (row.status === '未查看') {
    //     updateStatus(row);
    // }
    // 数据拷贝
    informModel.value.content = row.content;
    if(myQuillEditor.value){
        myQuillEditor.value.setHTML(informModel.value.content);
    }
    informModel.value.status = row.status;
    informModel.value.startTime = row.startTime;
    informModel.value.endTime = row.endTime;
    informModel.value.title = row.title;
    // 扩展ID属性，需要传输给后台
    informModel.value.informId = row.informId;
  }




</script>
<template>
    <div class="card-container">
        <el-card class="page-container">
            <template #header>
                <div class="header">
                    <span style="font-size: 14px;"><b>通知公告</b></span>
                    <div class="extra">
                        <el-button type="success" @click="exportSelected()" plain>导出</el-button>
                        <el-button type="danger" @click="deleteSelected()">批量删除</el-button>
                        <el-button type="primary" @click="dialogVisible=true;title='添加公告';clearData()">添加公告</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="informs" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="140" type="index"> </el-table-column>
                <el-table-column label="标题" width="200" prop="title"></el-table-column>
                <el-table-column label="状态" width="200" prop="status"></el-table-column>
                <el-table-column label="开始时间" width="230" prop="startTime"></el-table-column>
                <el-table-column label="结束时间" width="230" prop="endTime"></el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="deleteInform(row)"></el-button>
                        <el-button :icon="BellFilled" circle plain type="success" @click="showInform(row)"></el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>

            <el-dialog v-model="dialogVisible" :title="title" width="50%" >
                <el-form :model="informModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                    <el-form-item label="通知标题" prop="title">
                        <el-input v-model="informModel.title" minlength="1"></el-input>
                    </el-form-item>
                    <el-form-item label="通知内容" prop="content">
                        <div>
                            <QuillEditor ref="myQuillEditor"
                            theme="snow"
                            v-model:content="informModel.content"
                            :options="data.editorOption"
                            contentType="html"
                            @update:content="onContentChange"
                            />
                    </div>
                    </el-form-item>
                    <el-form-item label="开始时间" prop="startTime">
                        <el-date-picker v-model="informModel.startTime" type="datetime" placeholder="选择开始时间"
                            class="custom-date-picker" />
                    </el-form-item>
                    <el-form-item label="结束时间" prop="endTime">
                        <el-date-picker v-model="informModel.endTime" type="datetime" placeholder="选择结束时间"
                            class="custom-date-picker" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="title=='添加公告'?addInform():updateInform()"> 确认 </el-button>
                    </span>
                </template>
            </el-dialog>

            <el-dialog v-model="informDialog" width="30%" :top="'calc(200px)'">
                <el-form :model="informModel" label-width="100px" style="padding-right: 30px">
                    <el-form-item label="通知标题:" prop="title">
                        {{ informModel.title }}
                    </el-form-item>
                    <el-form-item  label="通知内容:" prop="content">
                        <!-- {{ informModel.content }} -->
                        <el-scrollbar style="height: 200px;">
                        <div style="border: 2px solid #ebeef5; padding:5px ;width: 280px; height: 200px;" v-html="informModel.content"></div>
                    </el-scrollbar>
                    </el-form-item>
                    <el-form-item  label="开始时间:" prop="startTime">
                        {{ informModel.startTime }}
                    </el-form-item>
                    <el-form-item label="结束时间:" prop="endTime">
                        {{ informModel.endTime }}
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <!-- <el-button @click="informDialog = false " type="primary">确定</el-button> -->
                        <el-button @click="informDialog = false" type="primary" v-if="informModel.status === '已查看'">确定</el-button>
                        <el-button @click="informDialog = false; updateStatus(informModel)" type="primary" v-else>确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
    <el-pagination class="el-p" v-model:current-page="currentPage" v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]" :background="true" layout="jumper,total, sizes, prev, pager, next " :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<style lang="scss" scoped>
    .card-container {
        height: 520px;
        /* 设置合适的固定高度 */
        overflow: auto;
    }

    .page-container {
        min-height: 100%;
        box-sizing: border-box;

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .extra {
                display: flex;
                align-items: center;

                .el-input {
                    margin-right: 400px;
                }
            }
        }
    }

    .custom-date-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
    }

    .el-p {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .input-with-select {
        background-color: var(--el-fill-color-blank);
    }
    // 调整样式
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}

</style>